﻿using SienSchoofsProject.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;

namespace SienSchoofsProject.Controllers
{
    public class ContactController : BaseController
    {
        // Pagina openen
        // GET: /Contact/

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        //E-mail versturen
        // POST: /Contact/
        [HttpPost]
        public ActionResult Index(ContactModel model)
        {
            try
            {
                var van = new MailAddress("Sienstestemail@gmail.com", "FilmDb");
                var naar = new MailAddress("Sienstestemail@gmail.com", "Sien Schoofs");
                const string wachtwoord = "Sientest";
                string onderwerp = "[FilmDb] " + model.Titel;
                string boodschap = "Van: " + model.Email + "\nOnderwerp: " + model.Titel + "\n\nBoodschap:\n" + model.Bericht;

                SmtpClient client = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(van.Address, wachtwoord)
                };
                MailMessage msg = new MailMessage();
                msg.From = van;
                msg.To.Add(naar);

                msg.Subject = onderwerp;
                msg.Body = boodschap;

                client.Send(msg);

                return RedirectToAction("Succes");
            }
            catch (Exception e)
            {
                //Server.MapPath("~") = de root-map van het project
                string pad = Server.MapPath("~") + "/Logging/Log.txt";
                if (!System.IO.File.Exists(pad))
                {
                    System.IO.File.Create(pad);
                }

                using (StreamWriter swTracing = System.IO.File.AppendText(pad))
                {
                    swTracing.Write("\n\nDatum/Tijd: " + DateTime.Now + "\nException:\n" + e.StackTrace);
                }
            }
            return View();
        }

        //succesvol mail verzonden tonen
        public ActionResult Succes()
        {
            ViewData["titel"] = Resources.Resources.ContactSentTitle;
            ViewData["h2"] = Resources.Resources.ContactSentH2;
            ViewData["bericht"] = Resources.Resources.ContactSentBercith;

            return View();
        }
    }
}
